package Thread;

/**
 * Created with IntelliJ IDEA.
 * Description: 线程模式之阻塞队列
 * 注意每个方法中count值的变化
 */
class MyBlockingQueue2 {
    private Integer[] values = new Integer[20];
    private int start = 0;
    private int end = 0;
    private int count = 0;
    private Object locker = new Object();

    public void put(int value) {
        synchronized (locker) {
            if(values.length == count) {
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            values[end++] = value;
            count++;
            if(end == values.length) {
                end = 0;
            }
            locker.notify();
        }
    }

    public Integer take() {
        synchronized (locker) {
            if(count == 0) {
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            int ret = values[start++];
            count--;
            if(start == values.length) {
                start = 0;
            }
            locker.notify();
            return ret;
        }
    }


}

public class ThreadDemo33 {
    private static MyBlockingQueue2 queue = new MyBlockingQueue2();
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while(true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    queue.put(i);
                    System.out.println("入队列：" + i);
                    i++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                while(true) {
                    System.out.println("出队列：" + queue.take());
                }
            }
        });
        t1.start();
        t2.start();
    }
}
